#
#  Copyright 2012 Autodesk, Inc.  All rights reserved.
#
#  Use of this software is subject to the terms of the Autodesk license 
#  agreement provided at the time of installation or download, or which 
#  otherwise accompanies this software in either electronic or hard copy form.   
#

__copyright__ = "Copyright (c) 2012 Autodesk, Inc."
__version__ = "1.4"
__date__ = "Date: 2012/04/30"
__author__ = "Cyrille Fauvel <cyrille.fauvel@autodesk.com>"
__credits__ = ["Cyrille Fauvel"]
__status__ = "Production"

#From:
#http://around-the-corner.typepad.com/adn/2012/10/debugging-python-in-maya-with-eclipsepydev.html

'''
Advanced concepts
import & reload()

One important concept in Python is that import is executed only once. 
If you modify your code, you need to use the function reload() to force Maya 
to refresh the code changes. The debugmaya.py comes with an ImporterController 
which will take care of cleaning your Python environment so you do not have 
to care about this at all. However, you should be aware of what is done in 
the background. When you load a Python module, Python keeps an internal 
reference in a dictionary to avoid having to reload the same file definition 
multiple time. While it is good for performance and cross references, it 
is a disaster for someone who wants to debug the code, because it would mean 
to restart the application each time. To avoid this problem, the debugger 
creates a singleton instance of the controller and the controller makes a 
copy of the references dictionary. Then it replaces the built-in import 
function. From there any new imported modules would be reloaded each time 
when requested, but not the ones which were already loaded before 
the debugger started.
'''


import sys, imp, builtins
#sys.path.append("C:/Program Files/Eclipse/plugins/org.python.pydev_2.6.0.2012062818/pysrc")

import pydevd
def startDebug():
    global gMayaImportController
    pydevd.settrace()
    gMayaImportController = MayaImportController()

def debugModule( m1 ):
    f, filename, description = imp.find_module(m1)
    package = imp.load_module(m1, f, filename, description)

import zipimport
def mayaPythonZip( m1 ):
    importer = zipimport.zipimporter('python26.zip')
    for m1 in ['zipimport_get_code', 'zipimport_get_source']:
        source = importer.get_source( m1)
    return source

'''
def getCurrentExecuterControl():
    # Returns the current executer control.
    sCommandExecuterTabs = maya.mel.eval('$t = $gCommandExecuterTabs')
    # get tab array
    aCommandExecuterTabs = maya.cmds.tabLayout(sCommandExecuterTabs, query=True, childArray=True)
    # get selected tab index
    selTabIdx = maya.cmds.tabLayout(sCommandExecuterTabs, query=True, selectTabIndex=True) - 1
    # get the tab at the index
    curFormLayout = aCommandExecuterTabs [selTabIdx]
    # get the formLayout children in this tab (according to how we built it)
    tabChldrn =  maya.cmds.formLayout(curFormLayout, query=True, childArray=True)
    # get the formLayout's first child which should be the cmdScrollFieldExecuter
    curExecuter = tabChldrn[0]
    return curExecuter

def getCurrentExecuterCode():
    curExecuter = getCurrentExecuterControl()
    #int $len =`cmdScrollFieldExecuter -q -textLength $curExecuter`;
    #string $text1 =`cmdScrollFieldExecuter -q -selectedText $curExecuter`;
    #string $text2 =`cmdScrollFieldExecuter -q -text $curExecuter`;
    text = maya.cmds.cmdScrollFieldExecuter(curExecuter,query=True,text=True)
    return text
'''

class MayaImportController(object):
    singleton = None

    def __new__(cls, *args, **kwargs):
        if not cls.singleton:
            cls.singleton = super(MayaImportController, cls).__new__(cls, *args, **kwargs)
            # Creates an instance and installs as the global importer
            cls.singleton.previousModules = sys.modules.copy()
            cls.singleton .__import__ = builtins.__import__
            #cls.singleton .__import__ = __import__
            builtins.__import__ = cls.singleton ._import_
            #__import__ = cls.singleton ._import_
            cls.singleton.newModules = {}
        return cls.singleton
    
    def __init__(self):
        pass
        
    def _import_(self, name, globals=None, locals=None, fromlist=[], level=-1):
        if name in self.newModules.keys():
            if not name in self.previousModules.keys():
                # Force reload when name next imported
                del(sys.modules[name])
        #result = builtins.apply(self.__import__, (name, globals, locals, fromlist))
        result = self.__import__( name, globals, locals, fromlist )
        self.newModules[name] = 1
        return result
        
    def uninstall(self):
        for name in self.newModules.keys():
            if not name in self.previousModules.keys():
                # Force reload when name next imported
                del(sys.modules[name])
        builtins.__import__ = self.__import__
        #__import__ = self.__import__